package com.bonc.datasource;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @ClassName DataSourceAspect
 * @Description: 数据源切面
 * @Author chenGJ
 * @Date 2021/12/21 11:05
 * @Version V1.0
**/
@Aspect
@Component
public class DataSourceAspect implements Ordered {

    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 设置切点
     */
    @Pointcut("@annotation(com.bonc.datasource.DataSource)")
    public void  dataSourcePointCut(){

    }

    /**
     * 切面
     * @param point
     * @return
     * @throws Throwable
     */
    @Around("dataSourcePointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method =signature.getMethod();
        DataSource ds=method.getAnnotation(DataSource.class);
        if (ds ==null) {
            // 当数据源为空时 配置默认数据源为第一个
            DynamicDataSourceContextHolder.setDataSource(DataSourceNames.DEFAULT);
            logger.info("set datasource is "+ DataSourceNames.DEFAULT);
        } else  {
            // 根据既定已配置数据源来设定
            DynamicDataSourceContextHolder.setDataSource(ds.name());
            logger.info("set datasource is " + ds.name());
        }
        try {
            return point.proceed();
        } finally {
            DynamicDataSourceContextHolder.clearDataSource();
            logger.info("clean datasource");
        }
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
